import re

from django.db.models import QuerySet
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import mixins, viewsets, status
from api.models.InventoryModel import WmsReceiptOrder, WmsReceiptOrderDetail, WmsItemSku, WmsInventory
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from drf_camel_case.parser import CamelCaseJSONParser
from drf_camel_case.render import CamelCaseJSONRenderer


from api.serializers.InventorySerializer import ReceiptOrderSerializer, ReceiptOrderDetailSerializer, \
    ItemSkuWithReceiptOrderEditSerializer, BoardListSerializer
from api.filters import ItemSkuFilter, BoardListFilter
from api.utils.jsonResponse import SuccessResponse, ErrorResponse
from api.utils.pageUtils import PageNumberPagination
from api.utils.viewMixin import UpdateAllModelMixin


class ReceiptOrderListViewSet(
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.CreateModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = WmsReceiptOrder.objects.all()
    serializer_class = ReceiptOrderSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = ['order_status','opt_type','biz_order_no','order_no']
    pagination_class = PageNumberPagination # 分页功能
    parser_classes = (CamelCaseJSONParser,)  # 自动将入参驼峰转下划线
    renderer_classes = (CamelCaseJSONRenderer,)  # 自动将响应下划线转驼峰


@extend_schema_view(
    list=extend_schema(summary="获取入库订单列表"),
    retrieve=extend_schema(summary="获取单个入库订单详情"),
    create=extend_schema(summary="创建入库订单"),
    update=extend_schema(summary="更新入库订单"),
    partial_update=extend_schema(summary="部分更新入库订单"),
    destroy=extend_schema(summary="删除入库订单"),
)
class ReceiptOrderViewSet(
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = WmsReceiptOrder.objects.all().order_by("id")
    serializer_class = ReceiptOrderSerializer
    filter_backends = [SearchFilter, DjangoFilterBackend]  #
    # url里面若是携带参数，则根据参数过滤结果集
    filterset_fields = ['order_status','opt_type','biz_order_no','order_no']
    # 分页组件
    pagination_class = PageNumberPagination

    parser_classes = (CamelCaseJSONParser,)  # 自动将入参驼峰转下划线
    renderer_classes = (CamelCaseJSONRenderer,)  # 自动将响应下划线转驼峰

    # @extend_schema(
    #     summary="获取入库订单列表",
    #     description="返回所有入库订单列表，支持分页。",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def list(self, request, *args, **kwargs):
    #     receipt_order_id = self.kwargs.get('receipt_order_id')
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # 传入的order_id为0的话检索全部入库单详情，否在则根据order_id筛选一遍
    #     if receipt_order_id != '0' :
    #         queryset = queryset.filter(id=receipt_order_id).first()
    #         serializer = self.get_serializer(instance=queryset,many=False)
    #         return SuccessResponse(serializer.data)
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return SuccessResponse(serializer.data,total=queryset.count())
    #     serializer = self.get_serializer(queryset, many=True)
    #     return SuccessResponse(serializer.data,total=queryset.count())

    # @extend_schema(
    #     summary="新增入库订单列表",
    #     description="插入入库订单和入库详情订单，根据order_status判别是完成入库还是暂存订单。",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def create(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     validated_data = serializer.validated_data
    #     details_data = validated_data.pop('details')
    #     receipt_order = WmsReceiptOrder.objects.create(**validated_data)
    #     for detail in details_data:
    #         WmsReceiptOrderDetail.objects.create(order=receipt_order, **detail)
    #     headers = self.get_success_headers(serializer.data)
    #     return SuccessResponse(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    # @extend_schema(
    #     summary="更新入库订单列表",
    #     description="插入入库订单和入库详情订单，根据order_status判别是完成入库还是暂存订单。",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def update(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     validated_data = serializer.validated_data
    #     details_data = validated_data.pop('details')
    #     receipt_order = WmsReceiptOrder.objects.filter(id=validated_data.get('id'))
    #     receipt_order.update(**validated_data)
    #     for detail in details_data:
    #         if detail.get('id') is None:
    #             WmsReceiptOrderDetail.objects.create(order=WmsReceiptOrder.objects.get(id=validated_data.get('id')),**detail)
    #         else:
    #             WmsReceiptOrderDetail.objects.filter(id=detail['id']).update(**detail)
    #     headers = self.get_success_headers(serializer.data)
    #     return SuccessResponse(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    # @extend_schema(
    #     summary="删除入库订单列表",
    #     description="插入入库订单和入库详情订单，根据order_status判别是完成入库还是暂存订单。",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def destroy(self, request, *args, **kwargs):
    #     receipt_order_id = self.kwargs.get('receipt_order_id')
    #     # 根据id查出来detail表，先删除外键表数据
    #     try:
    #         receipt_order_detail = WmsReceiptOrderDetail.objects.filter(order_id=receipt_order_id)
    #         for detail in receipt_order_detail:
    #             detail.delete()
    #     except WmsReceiptOrder.DoesNotExist:
    #         pass
    #     # 查询receipt_order_id所指定的模型对象
    #     try:
    #         receipt_order = WmsReceiptOrder.objects.get(id=receipt_order_id)
    #     except WmsReceiptOrder.DoesNotExist:
    #         return ErrorResponse(status=status.HTTP_404_NOT_FOUND, msg='没有对应数据')
    #     receipt_order.delete()
    #     return SuccessResponse(status=200, msg='删除成功')





@extend_schema_view(
    list=extend_schema(summary="获取入库订单详情列表"),
    retrieve=extend_schema(summary="获取单个入库订单详情"),
    create=extend_schema(summary="创建入库订单详情"),
    update=extend_schema(summary="更新入库订单详情"),
    partial_update=extend_schema(summary="部分更新入库订单详情"),
    destroy=extend_schema(summary="删除入库订单详情"),
)
class ReceiptOrderDetailViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = WmsReceiptOrderDetail.objects.all().order_by("id")
    serializer_class = ReceiptOrderDetailSerializer
    filter_backends = [SearchFilter, DjangoFilterBackend]#
    filterset_fields = ['order_id']
    parser_classes = (CamelCaseJSONParser,)  # 自动将入参驼峰转下划线
    renderer_classes = (CamelCaseJSONRenderer,)  # 自动将响应下划线转驼峰
    # @extend_schema(
    #     summary="获取入库订单列表详情",
    #     description="返回所有入库订单列表，支持分页，支持传入入库订单id（19位）查询，id为0时返回全部入库订单详情",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def list(self, request, *args, **kwargs):
    #     order_id = self.kwargs.get('order_id')
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # 传入的order_id为0的话检索全部入库单详情，否在则根据order_id筛选一遍
    #     if order_id != '0' :
    #         queryset = queryset.filter(order_id = order_id)
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return SuccessResponse(serializer.data,total=queryset.count())
    #     serializer = self.get_serializer(queryset, many=True)
    #     return SuccessResponse(serializer.data,total=queryset.count())

    # @extend_schema(
    #     summary="删除入库订单列表详情",
    #     description="",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def destroy(self, request, *args, **kwargs):
    #     receipt_order_detail_id = self.kwargs.get('order_id')
    #     # 查询receipt_order_detail_id所指定的模型对象
    #     try:
    #         receipt_order_detail = WmsReceiptOrderDetail.objects.get(id=receipt_order_detail_id)
    #     except WmsReceiptOrderDetail.DoesNotExist:
    #         return ErrorResponse(status=status.HTTP_404_NOT_FOUND,msg='没有查询到数据')
    #     receipt_order_detail.delete()
    #     return SuccessResponse(status=200,msg = '删除成功')



# TODO,修改注释
@extend_schema_view(
    list=extend_schema(summary="获取入库订单详情列表"),
    retrieve=extend_schema(summary="获取单个入库订单详情"),
    create=extend_schema(summary="创建入库订单详情"),
    update=extend_schema(summary="更新入库订单详情"),
    partial_update=extend_schema(summary="部分更新入库订单详情"),
    destroy=extend_schema(summary="删除入库订单详情"),
)
class ItemSkuViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = WmsItemSku.objects.all()
    serializer_class = ItemSkuWithReceiptOrderEditSerializer
    filter_backends = [SearchFilter, OrderingFilter,DjangoFilterBackend]
    filterset_class = ItemSkuFilter
    pagination_class = PageNumberPagination
    ordering_fields = ['id']
    parser_classes = (CamelCaseJSONParser,)  # 自动将入参驼峰转下划线
    renderer_classes = (CamelCaseJSONRenderer,)  # 自动将响应下划线转驼峰

    # @extend_schema(
    #     summary="获取入库订单列表",
    #     description="返回所有入库订单列表，支持分页。",
    #     responses={200: ReceiptOrderSerializer(many=True)}
    # )
    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     # todo 过滤逻辑，因为业务要求根据从表进行数据过滤，过滤器暂时未查询到比较好的方法、
    #     # 商品名称
    #     item_name = request.query_params.get('itemName')
    #     # 商品编号
    #     item_code = request.query_params.get('itemCode')
    #     # 规格名称
    #     sku_name = request.query_params.get('skuName')
    #     # 规格编号
    #     sku_bar_code = request.query_params.get('barcode')
    #     if item_name is not None:
    #         queryset = queryset.filter(item__item_name__contains=item_name)

    #     if item_code is not None:
    #         queryset = queryset.filter(item__item_code = item_code)

    #     if sku_name is not None:
    #         queryset = queryset.filter(sku_name__contains = sku_name)

    #     if sku_bar_code is not None:
    #         if queryset.filter(barcode = sku_bar_code).exists():
    #             queryset = queryset.filter(barcode = sku_bar_code)
    #         else:
    #             queryset = queryset.filter(sku_code=sku_bar_code)
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return SuccessResponse(serializer.data, total=queryset.count())
    #     serializer = self.get_serializer(queryset, many=True)
    #     return SuccessResponse(serializer.data, total=queryset.count())

class BoardListViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.DestroyModelMixin,  # 添加删除功能
    UpdateAllModelMixin,
    viewsets.GenericViewSet
):
    queryset = WmsInventory.objects.all()
    serializer_class = BoardListSerializer
    filter_backends = [SearchFilter, OrderingFilter, DjangoFilterBackend]  #
    # url里面若是携带参数，则根据参数过滤结果集
    filterset_class = BoardListFilter
    ordering_fields = ['warehouse_id','sku_id']
    ordering = ('warehouse_id')
    parser_classes = (CamelCaseJSONParser,)  # 自动将入参驼峰转下划线
    renderer_classes = (CamelCaseJSONRenderer,)  # 自动将响应下划线转驼峰

    pagination_class = PageNumberPagination

    # parser_classes = (CamelCaseJSONParser,)  # 自动将入参驼峰转下划线
    # renderer_classes = (CamelCaseJSONRenderer,)  # 自动将响应下划线转驼峰

    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     order_by_type_or_sku_id = self.kwargs.get('type')
    #     # 前端页面展示的传入的type类型进行排序字段展示
    #     if order_by_type_or_sku_id == 'warehouse':
    #         queryset = queryset.order_by('warehouse_id')
    #     elif  order_by_type_or_sku_id == 'item':
    #         queryset = queryset.order_by('sku_id')
    #         # 订单根据sku_id调用库存返回对应的list,里面包含对应的数量和物品单价和对应的仓库id
    #         queryset = queryset.filter(sku_id = order_by_type_or_sku_id)
    #     # 商品名称
    #     warehouse_id = request.query_params.get('warehouseId')
    #     # 商品名称
    #     item_name = request.query_params.get('itemName')
    #     # 商品编号
    #     item_code = request.query_params.get('itemCode')
    #     # 规格名称
    #     sku_name = request.query_params.get('skuName')
    #     # 规格编号
    #     sku_code = request.query_params.get('skuCode')

    #     if warehouse_id is not None:
    #         queryset = queryset.filter(warehouse_id = warehouse_id)

    #     if item_name is not None:
    #         queryset = queryset.filter(sku__item__item_name__contains = item_name)

    #     if item_code is not None:
    #         queryset = queryset.filter(sku__tem__item_code = item_code)

    #     if sku_name is not None:
    #         queryset = queryset.filter(sku__sku_name__contains= sku_name)

    #     if sku_code is not None:
    #         queryset = queryset.filter(sku__sku_code=sku_code)
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True)
    #         return SuccessResponse(serializer.data, total=queryset.count())
    #     serializer = self.get_serializer(queryset, many=True)
    #     return SuccessResponse(serializer.data, total=queryset.count())

    # def update(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data,many=True)
    #     serializer.is_valid(raise_exception=True)
    #     validated_data = serializer.validated_data
    #     for data in validated_data:
    #         quantity = data.get('quantity')
    #         sku_id = data.get('sku_id')
    #         wms_inventory_list = WmsInventory.objects.filter(sku_id = sku_id)
    #         for wms_inventory in wms_inventory_list:
    #             if wms_inventory.quantity > quantity:
    #                 wms_inventory.quantity = wms_inventory.quantity - quantity
    #                 wms_inventory.save()
    #                 break
    #             else:
    #                 quantity = quantity - wms_inventory.quantity
    #                 wms_inventory.quantity = 0
    #                 wms_inventory.save()
    #     headers = self.get_success_headers(serializer.data)
    #     return SuccessResponse(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


        # receipt_order = WmsReceiptOrder.objects.filter(id=validated_data.get('id'))
        # receipt_order.update(**validated_data)
        # for detail in details_data:
        #     if detail.get('id') is None:
        #         WmsReceiptOrderDetail.objects.create(order=WmsReceiptOrder.objects.get(id=validated_data.get('id')),**detail)
        #     else:
        #         WmsReceiptOrderDetail.objects.filter(id=detail['id']).update(**detail)
        # headers = self.get_success_headers(serializer.data)
        # return SuccessResponse(serializer.data, status=status.HTTP_201_CREATED, headers=headers)